<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="记录时间" prop="recordTime">
        <el-date-picker clearable
                        v-model="queryParams.recordTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择记录时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="患者id" prop="patientId">
        <el-input
            v-model="queryParams.patientId"
            placeholder="请输入患者id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病情变化" prop="conditionChange">
        <el-input
            v-model="queryParams.conditionChange"
            placeholder="请输入病情变化"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="员工id" prop="doctorId">
        <el-input
            v-model="queryParams.doctorId"
            placeholder="请输入员工id"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!--      <el-form-item label="住院登记表" prop=" registrationId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams. registrationId"-->
      <!--          placeholder="请输入住院登记表"-->
      <!--          clearable-->
      <!--          @keyup.enter="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['masterdocker:masterdockerlog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['masterdocker:masterdockerlog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['masterdocker:masterdockerlog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['masterdocker:masterdockerlog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="masterdockerlogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="诊断日志id" align="center" prop="logId" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="患者id" align="center" prop="patientId" />
      <el-table-column label="患者名字" align="center" prop="patient.realName" />
<!--      <el-table-column label="医生id" align="center" prop="doctorId" />-->
      <el-table-column label="病情变化" align="center" prop="conditionChange" />
      <el-table-column label="医生名字" align="center" prop="employee.name" />
      <el-table-column label="住院登记表id" align="center" prop="registrationId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['masterdocker:masterdockerlog:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['masterdocker:masterdockerlog:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改病人病情记录日志对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="masterdockerlogRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
                          v-model="form.recordTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="患者姓名">

            <el-select
                v-model="form.patientId"
                clearable
                placeholder="Select"
                style="width: 240px"
                @change="handlePatientChange"
            >
              <el-option
                  v-for="item in patientArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"

              />
            </el-select>

        </el-form-item>
        <!-- 新增：显示选中患者的 ID -->
        <el-form-item label="患者 ID" v-if="selectedPatientId!== null">
          <span>{{ selectedPatientId }}</span>
        </el-form-item>



        <el-form-item label="病情变化" prop="conditionChange">
          <el-input v-model="form.conditionChange" placeholder="请输入病情变化" />
        </el-form-item>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Masterdockerlog">
import {
  listMasterdockerlog,
  getMasterdockerlog,
  delMasterdockerlog,
  addMasterdockerlog,
  updateMasterdockerlog,
  getDocterId, listMasterdockerlog1
} from "@/api/masterdocker/masterdockerlog";
import {onMounted} from "vue";

const { proxy } = getCurrentInstance();
// 获取本地存储的登录者的id;
const userId=localStorage.getItem("userId");
let dockerid=ref(0);//登录获取医生的id
const query=ref({
  id:userId
})
const query1=computed(() => ({
  doctorId: dockerid.value
}));
// 获取含该医生病人的总数据
let patienttotal=ref({});
// 获取病人的关键数据
let patientArr=ref([]);
// 存储选中患者的 ID
const selectedPatientId = ref(null);

// 处理患者选择改变的事件
const handlePatientChange = (value) => {
  selectedPatientId.value = value;
};





console.log(dockerid.value);
const masterdockerlogList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    recordTime: null,
    patientId: null,
    conditionChange: null,
    doctorId: null,
    registrationId: null,
  },
  rules: {
    patientId: [
      { required: true, message: "患者id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询病人病情记录日志列表 */
function getList() {
  console.log(queryParams.value)
  loading.value = true;
  listMasterdockerlog(queryParams.value).then(response => {
    masterdockerlogList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log(masterdockerlogList.value);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    logId: null,
    recordTime: null,
    patientId: null,
    conditionChange: null,
    doctorId: dockerid.value,
    registrationId: null,
    ext2: null,
    ext3: null,
    ext4: null,
    ext5: null
  };
  proxy.resetForm("masterdockerlogRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  queryParams.value.doctorId=dockerid.value;


  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.logId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加病人病情记录日志";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _logId = row.logId || ids.value
  getMasterdockerlog(_logId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改病人病情记录日志";
  });
}
// 判断新增病人的 id 和时间是否重复的函数
function isDuplicate(patientList, newPatient) {
  return patientList.some(patient => {
    return patient.patientId === newPatient.patientId && patient.recordTime === newPatient.recordTime;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["masterdockerlogRef"].validate(valid => {
    if (valid) {


      if (form.value.logId != null) {
        updateMasterdockerlog(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        if(isDuplicate(masterdockerlogList.value,form.value)){
          alert("添加日期日期重复")
          return;
        }





        console.log(form.value);
        form.value.doctorId=dockerid.value;
        form.value.registrationId=patientArr.value.find(item => item.id == form.value.patientId).registrationId;
        console.log(form.value);

        addMasterdockerlog(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _logIds = row.logId || ids.value;
  proxy.$modal.confirm('是否确认删除病人病情记录日志编号为"' + _logIds + '"的数据项？').then(function() {
    return delMasterdockerlog(_logIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('masterdocker/masterdockerlog/export', {
    ...queryParams.value
  }, `masterdockerlog_${new Date().getTime()}.xlsx`)
}

onMounted(() => {

  getDocterId(query.value).then(response => {
    console.log(response);
    dockerid.value=response.myuserId;
    queryParams.value={
      pageNum: 1,
          pageSize: 10,
        recordTime: null,
        patientId: null,
        conditionChange: null,
        doctorId: response.myuserId,
        registrationId: null,
    };
    console.log(queryParams.value);
    console.log(query1.value);
    getList();
    listMasterdockerlog1(query1.value).then(response => {
      patienttotal.value=response.rows;
      patientArr.value=patienttotal.value.map(item => {
        return {
          id: item.patientId,
          name: item.patient.realName,
          registrationId:item.registrationId
        };
      });

      console.log(patienttotal.value);
      console.log(patientArr.value);

    })


  });


})
</script>
